/*
 * Copyright (c) 2012 RTCLab
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 */

package com.rtckit {
import mx.controls.VideoDisplay;
import mx.core.mx_internal;
import mx.core.Application;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.Camera;
import flash.system.Security;
import flash.system.SecurityPanel;

public class VideoContainer extends VideoDisplay {
	public var app:Application = null;
	public var video:Video = null;
	public var preview:Boolean = false;
	
    public function VideoContainer(app:Application, width:Number, height:Number, preview:Boolean) {
    	super();
    	this.width = width;
    	this.height = height;
    	this.app = app;
    	this.preview = preview;

    	if (preview) {
    		show();
    		showPreview();
    	}
    }

    // does not work for some reason
    private function clear():void {
        mx_internal::videoPlayer.clear();
    }
    
    // video container
    
    private function show():void {
    	if (parent != app)
    		app.addChild(this);
    }
    
    private function hide():void {
    	if (parent == app)
    		app.removeChild(this);
    }
    
    // remote video stream
    
    private function showVideo():void {
    	if (!video)
    		return;

    	if (preview)
    		hidePreview();
    	else
    		show();
    	
    	if (video.parent != this)
    		addChild(video);
    }
    
    private function hideVideo():void {
    	if (video && video.parent == this)
    		removeChild(video);
    	
    	if (preview)
    		showPreview();
    	else
    		hide();
    }
    
    private function videoPlaying():Boolean {
    	return video && video.parent == this;
    }
    
    // stream
    
    public function switchToStream(stream:NetStream):void {
    	if (video) {
    		if (videoPlaying())
    			hideVideo();
    		video.attachNetStream(null);
    		video = null;
    	}
    	if (stream) {
    		video = new Video(width, height);
    		video.attachNetStream(stream);
    		showVideo();
    	}
    }

    // preview

    private var previewOn:Boolean = false;

    private function showPreview():void {
    	if (previewOn)
    		return;

		var camera:Camera = Camera.getCamera();
		if (!camera) {
			Logger.error('No camera available');
			return;
		}
		if (camera.muted)
			Security.showSettings(SecurityPanel.PRIVACY);
		camera.setMode(width, height, 15);
		attachCamera(camera);
		previewOn = true;
    }

    private function hidePreview():void {
    	previewOn = false;
		attachCamera(null);
	}
}
}
